﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.BizExtensions;
using User.Api.Dto.Depart;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace User.Api.Controllers
{
    public class DepartController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(DepartController));
        private FsssdqfybjyEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new FsssdqfybjyEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取所有科室信息
        /// </summary>
        /// <param name="branchName">分院名称(小写拼音),为空时表示所有分院</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetAll")]
        public GetAllResponse GetAll(string branchName = "")
        {
            //var branchNo = DepartExtensions.ToBranchNo(branchName);
            var departs = _ctx.Departs.Where(x => x.RecStatus == 1);
            if (!string.IsNullOrEmpty(branchName))
            {
                departs = departs.Where(x => x.Loc == branchName);
            }

            var departsList = departs.OrderBy(x => x.Sort).ThenBy(x => x.DeptId).ToList();

            return new GetAllResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Departs = departsList.Select(x => new GetAllResponse.Depart
                {
                    BranchName = x.Loc, //DepartExtensions.ToBranchName(x.BranchNo),
                    DepartId = x.DeptId,
                    DepartName = x.DeptName
                }).OrderBy(x => x.DepartName).ToList()
            };
        }

        /// <summary>
        /// 根据科室院内编号获取科室信息
        /// </summary>
        /// <param name="deptId">科室院内编号</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetByDeptId")]
        public GetByDeptIdResponse GetByDeptId(string deptId)
        {
            var depart = _ctx.Departs.FirstOrDefault(x => x.DeptId == deptId);
            if (depart == null)
            {
                return new GetByDeptIdResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到科室",
                };
            }

            var doctors = _ctx.Doctors.Where(x => x.RecStatus == 1 && x.DeptId == deptId)
                .OrderBy(x => x.Sort).ThenBy(x => x.DoctorId).ToList();

            return new GetByDeptIdResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Name = depart.DeptName,
                Position = depart.Loc,
                Desc = string.IsNullOrEmpty(depart.Desc) ? "暂无介绍" : ReplaceHtmlTag(depart.Desc),
                Drs = doctors.Select(x => new GetByDeptIdResponse.Dr
                {
                    DoctorId = x.DoctorId,
                    DeptId = x.DeptId,
                    Name = x.DoctorName,
                    Sex = DoctorExtensions.ToZhSex(x.Gender),
                    Title = x.Title
                }).ToList()
            };            
        }

        /// <summary>
        /// 搜索科室或医生
        /// </summary>
        /// <param name="keyword">科室或医生的名称，包含关系</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("SearchDepartOrDr")]
        public SearchDepartOrDrResponse SearchDepartOrDr(string keyword)
        {
            var departs = _ctx.Departs.Where(x => x.RecStatus == 1 && x.DeptName.Contains(keyword))
                .OrderBy(x => x.Sort).ThenBy(x => x.DeptId).ToList();

            var doctors = _ctx.Doctors.Where(x => x.RecStatus == 1 && x.DoctorName.Contains(keyword))
                .OrderBy(x => x.Sort).ThenBy(x => x.DoctorId).ToList();

            return new SearchDepartOrDrResponse
            {
                ResultCode = "0",
                ResultMsg = "",
                Departs = departs.Select(x => new SearchDepartOrDrResponse.Depart
                {
                    DepartId = x.DeptId,
                    DepartName = x.DeptName
                }).ToList(),
                Drs = doctors.Select(x => new SearchDepartOrDrResponse.Dr
                {
                    DepartId = x.DeptId,
                    DepartName = x.DeptName,
                    DrId = x.DoctorId,
                    DrName = x.DoctorName,
                    Sex = x.Gender,
                    Title = x.Title
                }).ToList()
            };
        }

        /// <summary>
        /// 搜索科室或医生
        /// </summary>
        /// <param name="keyword">科室或医生的名称，包含关系</param>
        /// <param name="regType">预约，挂号</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("SearchDepartDr")]
        public SearchDepartOrDrResponse SearchDepartDr(string keyword,string regType="reg")
        {
            //预约
            if (regType == "book")
            {
                var departs = _ctx.Departs.Where(x => x.RecStatus == 1 && x.DeptName.Contains(keyword)).OrderBy(x => x.Sort).ThenBy(x => x.DeptId)
                    .Select(x => new SearchDepartOrDrResponse.Depart
                {
                    DepartId = x.DeptId,
                    DepartName = x.DeptName
                }).ToList();

                var doctors = CacheHelper.GetBookDoctors().Where(x => x.DoctorName.Contains(keyword))
                    .Select(x => new SearchDepartOrDrResponse.Dr
                    {
                        DepartId = x.DeptId,
                        DepartName = x.DeptName,
                        DrId = x.DoctorId,
                        DrName = x.DoctorName,
                        Sex = "",
                        Title = x.SubjectName
                    }).ToList();
                return new SearchDepartOrDrResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    Departs = departs,
                    Drs = doctors
                };
            }
            else
            {
                //挂号
                var departs = _ctx.Departs.Where(x => x.RecStatus == 1 && x.DeptName.Contains(keyword)).OrderBy(x => x.Sort).ThenBy(x => x.DeptId)
                    .Select(x => new SearchDepartOrDrResponse.Depart
                    {
                        DepartId = x.DeptId,
                        DepartName = x.DeptName
                    }).ToList();

                var doctors = CacheHelper.GetRegDoctors().Where(x => x.DoctorName.Contains(keyword))
                    .Select(x => new SearchDepartOrDrResponse.Dr
                    {
                        DepartId = x.DeptId,
                        DepartName = x.DeptName,
                        DrId = x.DoctorId,
                        DrName = x.DoctorName,
                        Sex = "",
                        Title = x.SubjectName
                    }).ToList();
                return new SearchDepartOrDrResponse
                {
                    ResultCode = "0",
                    ResultMsg = "",
                    Departs = departs,
                    Drs = doctors
                };

            }

        }

        /// <summary>
        /// 获取排班信息
        /// </summary>
        /// <param name="deptId">科室院内编号</param>
        /// <param name="doctorId">医生院内编号，为空表示查询科室内所有医生</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetTimeSlices")]
        public GetTimeSlicesResponse GetTimeSlices(string deptId, string doctorId)
        {
            var res = new GetTimeSlicesResponse();
            res.DefaultSelectedDay = "无剩余号源";
            res.Today = DateTime.Now.ToString("yyyy-MM-dd");
            res.RegDays = new List<GetTimeSlicesResponse.ScheduleDay>();
            for (int i = 0; i < 8; i++)
            {
                res.RegDays.Add(new GetTimeSlicesResponse.ScheduleDay
                {
                    Date = DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"),
                    IsFull = true,
                    TimeSlices = new List<GetTimeSlicesResponse.TimeSlice>()
                });
            }
            res.DeptName = _ctx.Departs.Where(x =>  x.DeptId == deptId).Select(x => x.DeptName).FirstOrDefault()??"";
               
            //// 获取排班
            //var request = new GetScheduleInfoRequest();
            //request.DeptId = deptId;
            //request.DoctorId = doctorId;
            //request.BeginDate = DateTime.Now.ToString("yyyy-MM-dd");
            //request.EndDate = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd");

            //GetScheduleInfoResponse response;
            //try
            //{
            //    var httpClient = InHttpClient.GetClient();
            //    var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetScheduleInfo", request).Result;
            //    responseMsg.EnsureSuccessStatusCode();
            //    response = responseMsg.Content.ReadAsAsync<GetScheduleInfoResponse>().Result;
            //}
            //catch (Exception ex)
            //{
            //    Logger.ErrorFormat("调用院内排班Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
            //    res.ResultCode = "1";
            //    res.ResultMsg = "获取排班超时";
            //    return res;
            //}

            //if (response.ResultCode != "0")
            //{
            //    res.ResultCode = "2";
            //    res.ResultMsg = response.ResultDesc;
            //    return res;
            //}

            //var scheduleInfos = response.ScheduleList;

            //foreach (var scheduleInfo in scheduleInfos)
            //{
            //    var scheduleDay = res.RegDays.First(x => x.Date == scheduleInfo.RegDate);
            //    if (scheduleInfo.TotalCount == "不限号" || scheduleInfo.LeaveCount.ToInt32OrDefault() > 0)
            //    {
            //        scheduleDay.IsFull = false;
            //        if (res.DefaultSelectedDay == "无剩余号源")
            //        {
            //            res.DefaultSelectedDay = scheduleInfo.RegDate;
            //        }
            //    }

            //    scheduleDay.TimeSlices.Add(new GetTimeSlicesResponse.TimeSlice
            //    {
            //        DeptId = scheduleInfo.DeptId,
            //        DeptName = scheduleInfo.DeptName,
            //        DoctorId = scheduleInfo.DoctorId,
            //        DoctorName = scheduleInfo.DoctorName,
            //        Title = scheduleInfo.Title,
            //        RegType = scheduleInfo.RegType,
            //        SliceName = scheduleInfo.TimeSlice,
            //        SliceStartTime = scheduleInfo.StartTime,
            //        SliceEndTime = scheduleInfo.EndTime,
            //        LeaveCount = scheduleInfo.LeaveCount.ToInt32OrDefault() < 0 ? 0 : scheduleInfo.LeaveCount.ToInt32OrDefault(),
            //        TotalCount = scheduleInfo.TotalCount.ToInt32OrDefault(),
            //        HasTimePoint = scheduleInfo.IsTimeFlag == "1",
            //        RegFee = scheduleInfo.Fee.ToDecimalOrDefault(),
            //        TreatFee = scheduleInfo.TreatFee.ToDecimalOrDefault(),
            //        OtherFee = scheduleInfo.OtherFee.ToDecimalOrDefault(),
            //        TotalFee = scheduleInfo.Fee.ToDecimalOrDefault() + scheduleInfo.TreatFee.ToDecimalOrDefault() + scheduleInfo.OtherFee.ToDecimalOrDefault()
            //    });
            //}

            res.ResultCode = "0";
            res.ResultMsg = "";
            return res;            
        }

        public static string ReplaceHtmlTag(string html, int length = 0)
        {
            string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
            strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");

            if (length > 0 && strText.Length > length)
                return strText.Substring(0, length);

            return strText;
        }
    }    
}
